const db = wx.cloud.database()
const Time = require('../../../utils/time/TimeUtil2')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    remian_num: 0, //剩余抽奖的次数
    prize_list: [{
        id: "001",
        icon: 'https://776f-womenlia-2gcdym6fb861b775-1331674006.tcb.qcloud.la/%E7%BA%BF%E6%9D%A1%E5%B0%8F%E7%8B%97/xiantiao21.png?sign=c63f9a35242f49ab8718084905f4b4b0&t=1736770493',
        name: '积分+10',
        active: false,
        num: 10,
      },
      {
        id: "002",
        icon: 'cloud://womenlia-2gcdym6fb861b775.776f-womenlia-2gcdym6fb861b775-1331674006/线条小狗/retouch_2025011319082456.png',
        name: '谢谢惠顾',
        active: false,
        num: 0
      },
      {
        id: "003",
        icon: 'https://776f-womenlia-2gcdym6fb861b775-1331674006.tcb.qcloud.la/%E7%BA%BF%E6%9D%A1%E5%B0%8F%E7%8B%97/xiaotiao25.png?sign=e6147d29b4b51004da8bb967895fc6e5&t=1736770621',
        name: '积分+3',
        active: false,
        num: 3
      },
      {
        id: "004",
        icon: 'https://776f-womenlia-2gcdym6fb861b775-1331674006.tcb.qcloud.la/%E7%BA%BF%E6%9D%A1%E5%B0%8F%E7%8B%97/xiaotiao22.png?sign=3363c2e4afae894bc3f2f180fe27b06f&t=1736770600',
        name: '积分+100',
        active: false,
        num: 100
      },
      {
        id: "005",
        icon: 'https://776f-womenlia-2gcdym6fb861b775-1331674006.tcb.qcloud.la/%E7%BA%BF%E6%9D%A1%E5%B0%8F%E7%8B%97/xiantiaoxiaogou3.png?sign=0e91d36bedbda529e4c5fd36c1756620&t=1736770573',
        name: '积分+8',
        active: false,
        num: 8
      },
      {
        id: "006",
        icon: 'https://776f-womenlia-2gcdym6fb861b775-1331674006.tcb.qcloud.la/%E7%BA%BF%E6%9D%A1%E5%B0%8F%E7%8B%97/xiantiao8.png?sign=addc962aa405a1bd8b4b284155be017f&t=1736770692',
        name: '派大星的奖励',
        active: false,
        num: 0
      },
      {
        id: "007",
        icon: 'https://776f-womenlia-2gcdym6fb861b775-1331674006.tcb.qcloud.la/%E7%BA%BF%E6%9D%A1%E5%B0%8F%E7%8B%97/xiantiao20.png?sign=77d15c21829a320b1d68e49cc145d46a&t=1736770654',
        name: '积分+1',
        active: false,
        num: 1
      },
      {
        id: "008",
        icon: 'https://776f-womenlia-2gcdym6fb861b775-1331674006.tcb.qcloud.la/%E7%BA%BF%E6%9D%A1%E5%B0%8F%E7%8B%97/xiantiao23.png?sign=3746ad98e1337c15df6a645dfd372063&t=1736770533',
        name: '积分+30',
        num: 30,
        active: false,
      },
    ],
    lock: false, //防止重复点击
    prizeListIndex: [0, 1, 2, 4, 7, 6, 5, 3], //抽奖顺序的索引
    luckIndex: null, //抽中的索引
    user: {}
  },


  onLoad: function (options) {
    let value = wx.getStorageSync('autt')
    this.setData({
      user: value.user
    })
    this.indexcs()
  },
  //抽奖次数判定
  indexcs() {
    // 获取当前时间存储到本地
    let time = new Date()
    //根据当前天生成日期
    let vaa = wx.getStorageSync('cjhd')
    if (vaa) {
      let sj = vaa.time + (24 * 60 * 60 * 1000)
      let dqsj = new Date()
      if (sj - dqsj.getTime() > 0) {
        console.log("还没过完今天")
        this.setData({
          remian_num: vaa.jh
        })
      } else {
        time.setHours(0, 0, 0, 0)
        console.log(time.getTime())
        //存到本地中去
        let data = {
          time: time.getTime(),
          jh: 3,
        }
        this.setData({
          remian_num: 3//默认三次免费
        })
        wx.setStorageSync('cjhd', data)
      }
    } else {
      console.log(2);
      //  获取当天0点的毫秒值
      time.setHours(0, 0, 0, 0)
      console.log(time.getTime())
      //存到本地中去
      let data = {
        time: time.getTime(),
        jh: 3,
      }
      wx.setStorageSync('cjhd', data)
      this.setData({
        remian_num: 3//默认三次免费
      })
    }
  },

  onShow: function () {

  },
  // 禁止弹框底层滑动
  catchTouchMove: function () {
    return false;
  },
  // 范围随机数
  randomRange(lower, upper) {
    return Math.floor(Math.random() * (upper - lower)) + lower;
  },
  // 抽奖活动
  async lottery(e) {
    //获取当前时间
    let da = new Date()
    let t = Time.formatDatetime(da)
    let uup = db.command
    // 防止重复点击
    if (this.data.lock) return
    let value = wx.getStorageSync('autt')
    this.setData({
      user: value.user
    })
    //存到本地中去
    let vaa = wx.getStorageSync('cjhd')
    let data = {
      time: vaa.time,
      jh: this.data.remian_num - 1,
    }
    wx.setStorageSync('cjhd', data)
    let s = --this.data.remian_num
    // 清空上一次选中的索引
    // 判断是否最后一次抽奖
    if (s >= 0) {
      this.setData({
        remian_num: s,
        lock: true,
        luckIndex: null
      })
      this.runLuck(80);
      // 调用抽奖接口，拿到相应的商品选中的索引luckIndex
      // 测试1s之后拿到索引
      setTimeout(() => {
        let id = "007"; //假设返回的中奖选项的id为这个,决定中奖项
        this.data.prize_list.forEach((item, index) => {
          if (item.id == id) {
            console.log('根据id拿到的当前的索引是', index)
            this.data.prizeListIndex.forEach((item0, index0) => {
              if (item0 == index) {
                console.log('获取相应的抽奖索引', index0)
                this.setData({
                  luckIndex: index0,
                })
                let v = {}
                let n = this.data.prize_list[index]
                let user
                let str
                let jjjjff
                if (e.jf) {
                  user = e
                  v = {
                    id: user._id,
                    jf: user.jf + n.num,
                    aut: user.aut,
                    sjk: user.databiuse,
                    user: user
                  }
                  str = "抽奖+" + n.num + "积分"
                  jjjjff = n.num - 5
                } else {
                  user = this.data.user
                  v = {
                    id: user._id,
                    jf: user.jf - 5 + n.num,
                    aut: user.aut,
                    sjk: user.databiuse,
                    user: user
                  }
                  console.log(n);
                  str = "抽奖" + ( (s>0)?'+'+n.num :n.num- 5) + "积分"
                  jjjjff = (s>0)?n.num : n.num- 5
                }
                wx.setStorageSync('autt', v)
                let oj = {
                  nr: str,
                  time: t
                }
                let arr = user.jfmingxi
                console.log(arr);
                arr.unshift(oj)
                console.log(arr);
                db.collection('users').doc(this.data.user._id).update({
                  data: {
                    // 表示指示数据库将字段自增 10
                    jf: uup.inc(jjjjff),
                    jfmingxi: arr
                  },
                  success: function (res) {
                    console.log(res)
                  }
                })
              }
            })
          }
        })
      }, 1000)
    } else {
      //没有免费次数
      // 使用积分抽奖
      wx.showModal({
        title: '提示',
        content: '没有免费次数,是否使用5积分',
        success: res => {
          if (res.confirm) {
            //连接数据库\
            let user = this.data.user
            user.jf = user.jf - 5
            console.log(user);
            if (user.jf < 0) {
              wx.showToast({
                title: '积分不够',
                icon: 'error',
                duration: 2000
              })
              return
            }
            let str = "抽奖-5积分"
            let oj = {
              nr: str,
              time: t
            }
            let arr = user.jfmingxi
            arr.unshift(oj)
            this.setData({
              remian_num: 1
            })
            this.lottery(user)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }

  },
  // 抽奖动画
  Timer: null,
  LotteryEnd: false, //抽奖结束
  nowRunIndex: 0, //ative样式的索引，
  luckChose(luckIndex) {
    return new Promise((resolve, reject) => {
      console.log('中奖索引啊啊啊啊啊啊啊啊啊啊啊啊啊啊', luckIndex)
      let that = this;
      let maxTime = this.randomRange(2500, 4000) //抽奖的时间2.5s-4s之间
      let time_speed = 0.01; //速率
      function lotteryRun(time) {
        let list = that.data.prize_list;
        that.Timer = setTimeout(() => {
          that.setList()
          if (that.LotteryEnd && luckIndex == that.nowRunIndex) {
            clearTimeout(that.Timer);
            that.LotteryEnd = false;
            that.setData({
              lock: false
            })
            resolve(list.filter(v => {
              return v.active
            }))
          } else {
            time_speed += 0.5;
            lotteryRun(time + (time_speed));
          }
        }, time);
      }
      lotteryRun(80);
      setTimeout(() => {
        this.LotteryEnd = true;
      }, maxTime);
    })
  },
  // 抽奖开始时候，未选中状态
  runLuck(time) {
    let that = this;
    if (this.nowRunIndex == 0) { //初始化从索引0开始显示抽奖激活的边框
      this.setData({
        'prize_list[0].active': true
      })
    }
    that.Timer = setTimeout(() => {
      that.setList()
      if (this.data.luckIndex == null || this.data.luckIndex == undefined) {
        that.runLuck(80)
      } else {
        that.luckChose(this.data.luckIndex).then(e => {
          wx.showToast({
            title: '抽中了' + e[0].name,
            icon: 'none'
          })
        })
      }
    }, time);
  },
  setList() {
    let list = this.data.prize_list;
    ++this.nowRunIndex;
    // console.log('现在的索引', this.nowRunIndex)
    this.nowRunIndex >= this.data.prizeListIndex.length ? this.nowRunIndex = 0 : '';
    let Pindex = this.data.prizeListIndex[this.nowRunIndex];
    // console.log('奖品列表对应的索引', Pindex)
    list.map((item, index) => {
      item.active = Pindex == index;
    })
    this.setData({
      prize_list: list
    })
  },

  //积分奖励
  JfJiangli() {
    let ine = this.data.luckIndex
    let n = this.data.prize_list[ine]
    if (n == 0) return
    db.collection('users').doc(this.data.user._id).update({
      data: {
        // 表示指示数据库将字段自增 10
        jf: uup.inc(n),
      },
      success: function (res) {
        console.log(res)
      }
    })
  }



})